﻿using System;
using System.Data;
using System.Windows.Forms;
using Relocation.Com;
using Relocation.Base;
using Relocation.Base.UI;
using Relocation.Data;

namespace Relocation.UI
{
	/// <summary>
	/// 项目维护窗体
	/// </summary>
	/// <remarks></remarks>
	public partial class ProjectsWindow : BaseForm
	{
		public Project Project
		{
			get;
			private set;
		}	

		public ProjectsWindow()
			: base()
		{
			InitializeComponent();
			Initialize();
			this.pro_nameTextBox.Select();
		}

		public ProjectsWindow(Session session)
			: base(session)
		{
			InitializeComponent();
			Initialize();
			this.pro_nameTextBox.Select();
		}

		/// <summary>
		/// 修改项目
		/// </summary>
		public ProjectsWindow(Session session, Project project)
			: this(session)
		{
			this.Project = project;
			this.SetValueToInput(project);			
			this.FieldIsChanged = false;
		}


		private void Initialize()
		{
			RoleInfo rInfo = new RoleInfo(Session.KEY_ROLE_ADMIN, Session.KEY_ROLE_OPERATOR);
			this.pro_nameTextBox.Tag = new ControlTag(Project.GetPropName(t => t.name), new ValidatorInfo(true), null, rInfo);
			this.pro_organizationTextBox.Tag = new ControlTag(Project.GetPropName(t => t.organization), null, null, rInfo);
			this.pro_remarkTextBox.Tag = new ControlTag(Project.GetPropName(t => t.remark), null, null, rInfo);
			this.DateTimePicker_proApproveTime.Tag = new ControlTag(Project.GetPropName(t => t.approve), null, null, rInfo);
			this.DateTimePicker_proReplyTime.Tag = new ControlTag(Project.GetPropName(t => t.reply), null, null, rInfo);
			this.save_bt.Tag = new ControlTag(rInfo);
		}


		/// <summary>
		/// 增加或修改后保存
		/// </summary>
		private void SaveButton_Click(object sender, EventArgs e)
		{
			try
			{
				if (!this.ValidatorAllControls())
					return;

				bool isNew=this.Project == null;
				if (isNew)
				{
					this.Project = this.Session.DataModel.Projects.CreateObject();
					this.Project.project_id = Relocation.Service.DataModel.GenerateID(Project);//是新增
					this.Project.created = DateTime.Now;
				}
				this.GetValueFromInput(this.Project);
				this.Project.updated = DateTime.Now;
				this.Session.DataModel.Save(Project);
				if (this.Session.GetMainTreeView() != null)	//如果是第一次进入系统，因为没有项目记录而添加项目，那么此时mainTreeView是为空的
				{
					this.Session.GetMainTreeView().RefreshNode(Project, isNew ? EntityState.Added : EntityState.Detached);					
				}
				this.FieldIsChanged = false;
				this.DialogResult = DialogResult.OK;
				this.Close();
			} catch (Exception error)
			{
				Log.Error(error.GetInnerExceptionMessage());
				MessageBoxShowInfo("操作失败！");
			}
		}
	}
}